<template>
	<view class="w-full">
		<view class="recorder flex items-center" v-if="device == 'pc'" :class="btnLine">
			<image @click="startRecord" style="width: 40px; height: 40px; cursor: pointer" src="@/static/voice.png"
				mode="">
			</image>
			<view class="" style="
                background: rgba(0, 0, 0, 0.2);
                border-radius: 14px;
                padding: 6px 14px;
                margin: 0 12px;
            ">
				<text style="
                    font-weight: 400;
                    font-size: 11px;
                    color: #ffffff;
                    line-height: 17px;
                ">{{Tiptext}}</text>
			</view>
			<image @click="stopRecord" style="width: 40px; height: 40px; cursor: pointer" src="@/static/end.png"
				mode="">
			</image>
			<view style="display: none" class="recorder-button" :class="[isRecording ? 'is-recording' : '']"
				@mousemove.stop="moveRecord" @mouseup.stop="stopRecord" @touchstart.stop.prevent="startRecord"
				@touchmove.stop="moveRecord" @touchend.stop="stopRecord">
				{{ !isRecording ? "按住说话" : "松开停止" }}
				<text v-if="showDate" class="now-date">{{ reDate }}</text>
			</view>
			<!-- <audio ref="audioRef"></audio> -->
		</view>
		<view class="recorder w-full flex items-center" v-else :class="btnLine">
			<!-- <image @click="startRecord" style="width: 40px; height: 40px; cursor: pointer" src="@/static/voice.png"
				mode="">
			</image> -->
			<!-- <image @click="stopRecord" style="width: 40px; height: 40px; cursor: pointer" src="@/static/end.png"
				mode="">
			</image> -->
			<view class="recorder-button" :class="[isRecording ? 'is-recording' : '']"
				@mousedown.stop.prevent="startRecord" @mousemove.stop="moveRecord" @mouseup.stop="stopRecord"
				@touchstart.stop.prevent="startRecord" @touchmove.stop="moveRecord" @touchend.stop="stopRecord">
				{{ !isRecording ? "按住说话" : "松开停止" }}
				<text v-if="showDate" class="now-date">{{ reDate }}</text>
			</view>
			<!-- <audio ref="audioRef"></audio> -->
		</view>
	</view>
</template>

<script>
	let that;
	let rec = null,
		isPressed = false,
		recTimer = null;
	import Recorder from "@/utils/recorder";
	import "recorder-core/src/engine/wav.js";
	import {
		getMemberConfig
	} from '../common/api/aivoice.js'
	import {
		useConversationStore
	} from "../store";
	import {
		member_id
	} from "../common/config.js";
	const conversationStore = useConversationStore()
	export default {
		props: {
			btnLine: {
				type: String,
				default: "",
			},
			showDate: {
				type: Boolean,
				default: false,
			},
			device: {
				type: String,
				default: 'pc'
			}
		},
		data() {
			return {
				isRecording: false,
				audioRef: null,
				SZR_CONFIG: {}, //微信配置
				wx: null, //微信实例
				ex: null, //微信录音
				Tiptext: '点击左侧图标开始，右边结束',
				sec: 0,
				min: 0,
				timer: null,
				reDate: "00:00",
				duration: 20,
				member_id: member_id
			};
		},
		// computed: {
		// 	...mapGetters(['isWeiXin', 'member_id']),
		// },
		async mounted() {
			console.log("是否公众号", this.isWeiXin());
			that = this;
			rec?.close();
			rec = null;
			recTimer && clearTimeout(recTimer);
			recTimer = null;

			// 微信公众
			// this.isWeiXin()
			if (this.isWeiXin()) {
				const res = await getMemberConfig()
				console.log("拿到配置", res, this.member_id);
				if (res.code == 1) {
					let obj = res.data;
					obj.member_id = this.member_id;
					this.SZR_CONFIG = obj;
				} else {
					that.$message.error("获取微信配置失败，请稍后再试");
				}
			}
			this.$eventBus.$on('ChangeTipsText', () => {
				this.Tiptext = '点击左侧图标开始，右边结束'
			})
		},
		beforeDestroy() {
			this.$eventBus.$off('sendMessage')
		},
		methods: {
			isWeiXin() {
				// #ifndef H5
				return false;
				// #endif
				var ua = navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
					console.log("微信公众号环境");
					return true;
				} else {
					return false;
				}
			},
			// 录音计时
			startDate() {
				clearInterval(this.timer);
				this.sec = 0;
				this.min = 0;
				this.timer = setInterval(() => {
					this.sec += this.duration / 1000;
					if (this.sec >= 60) {
						this.min++;
						this.sec = 0;
					}
					this.resetDate();
				}, this.duration);
			},
			// 播放时间
			resetDate() {
				let _s =
					this.sec < 10 ? "0" + parseInt(this.sec) : parseInt(this.sec);
				let _m = this.min < 10 ? "0" + this.min : this.min;
				this.reDate = _m + ":" + _s;
			},

			// 开始录音
			startRecord() {
				console.log(23423423432423, isPressed)

				if (isPressed) return;
				// this.Tiptext = '我正在聆听...'
				isPressed = true;
				console.log(123)
				console.log(rec)
				console.log(456)
				if (!rec) {
				console.log(789)
					rec = Recorder({
						type: "wav",
						bitRate: 16,
						sampleRate: 16000,
						member_id: member_id,
						...(this.SZR_CONFIG || {}),
					});
					console.log('rec')
					console.log(rec)
					console.log(789)
				}
				console.log('186rec')
				setTimeout(() => navigator.vibrate?.(70));

				recTimer && clearTimeout(recTimer);
				recTimer = setTimeout(() => {
					if (!isPressed) return;
					console.log('rec', rec)
					console.log('193')
					rec.open(
						() => {
							if (!isPressed) return;
							console.log(rec.isWx)
							if (rec.isWx) {
								rec.start(
									(blob, duration) => {
										isPressed = false;
										clearTimeout(recTimer);

										console.log(rec, that.isRecording)
										if (!rec || !that.isRecording) return;
										that.isRecording = false;

										rec.close();
										that.$emit("end-record", {
											file: new File(
												[blob],
												`audio-${Date.now()}.${
                                                ~blob.type.indexOf("wav")
                                                    ? "wav"
                                                    : "mp3"
                                            }`, {
													type: blob.type,
												}
											),
											duration,
										});
									},
									msg => {
										console.error(msg);
										rec.close();
										that.$emit("end-record");
									}
								);
							} else rec.start();

							that.isRecording = true;
							console.log("开始录音");
							this.startDate();
							that.$emit("start-record");
						},
						(msg, isUserNotAllow) => {
							console.log("录音出错", msg);
							that.$message.error(msg);
							that.isRecording = false;
						}
					);
				}, 50);
			},
			// 结束录音
			stopRecord() {

				isPressed = false;
				clearTimeout(recTimer);

				if (!rec || !that.isRecording) return;
				that.isRecording = false;
				// this.Tiptext = '正在思考中....'
				rec.stop(
					(blob, duration) => {
						clearInterval(this.timer);
						if (duration < 1000) {
							console.log("录音太短了");
							that.$emit("end-record");
							that.$message.info("录音太短了");
							return;
						}
						rec.close();
						let recordMsg = {
							file: new File(
								[blob],
								`audio-${Date.now()}.${
                                ~blob.type.indexOf("wav") ? "wav" : "mp3"
                            }`, {
									type: blob.type,
								}
							),
							duration,
						};
						console.log("录音成功", recordMsg);
						that.$emit("end-record", recordMsg);

						// 在这个地方传给数字人录音文件
						console.log(recordMsg.file)
						this.$eventBus.$emit("hiddenWrap")
						const id = new Date().getTime()
						// 如果正在说话，不发送消息
						// if (conversationStore.Speaking) return
						// conversationStore.ChangeSpeaking(true)

						this.$eventBus.$emit("sendMessage", {
							type: "H5_SZR_INSTRUCT",
							id,
							detail: {
								code: 3,
								value: recordMsg.file,
							},
							componentsType: 'RecorderButton',
							sendMessageType: 'voice'
						});
					},
					msg => {
						console.error("出错了", msg);
						msg && that.$message.error(msg);
						rec.close();
						that.$emit("end-record");
					}
				);
			},
			moveRecord(e) {},
		},
	};
</script>

<style lang="scss" scoped>
	.recorder {
		position: relative;

		&.row-btn {
			padding: 10px;

			.recorder-button {
				position: initial;
				width: 100%;
				border-radius: 6px;
				box-shadow: 0 0 7px 0px rgba(0, 0, 0, 0.3);
			}
		}

		&.circle {
			display: flex;
			justify-content: center;
			padding: 10px 10px;

			.recorder-button {
				position: relative;
				left: initial;
				bottom: initial;
				box-shadow: 0 0 7px 0px rgba(0, 0, 0, 0.3);
			}
		}

		.now-date {
			color: #333;
			font-size: 14px;
			position: absolute;
			top: -20px;
			left: 50%;
			transform: translateX(-50%);
		}
	}

	.recorder-button {
		// position: absolute;
		left: calc(50% - 70px);
		bottom: 20px;
		z-index: 10;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 40px;
		border-radius: 20px;
		font-size: 16px;
		color: #666666;
		background-color: #1890ff;
		background: linear-gradient(180deg, #F4F9FF 0%, #D3E7FF 100%);
		cursor: pointer;
		user-select: none;
		touch-callout: none;

		&.is-recording {
			transform: scale(1.01);
			background: #f5222d !important;
			color: #FFF !important
		}
	}
</style>